/**
 * Created By: sisopipo Project Team
 * Created Date: Mar 4, 2011
 */
package com.sisopipo.assetsportal.security.impl;

import java.util.List;

import com.sisopipo.assetsportal.security.IRoleManager;
import com.sisopipo.assetsportal.security.domain.Function;
import com.sisopipo.assetsportal.security.domain.Role;
import com.sisopipo.core.model.hibernate.BaseHibernateDAO;

/**
 * @author ribin
 * @version 1.0
 */
@SuppressWarnings("unchecked")
public class RoleManagerImpl extends BaseHibernateDAO implements IRoleManager {

	public Function getFunction(String funcCode) {
		return (Function) first(findByHQL("from Function where code = ?", funcCode));
	}

	public void saveOrUpdateFunction(Function func) {
		if (func.getId() == null || func.getId().trim().length() == 0)
			func.setId(null);
		getSession().saveOrUpdate(func);
	}

	public void removeFunction(Function func) {
		func = (Function) getSession().get(Function.class, func.getId());
		if (func != null)
			getSession().delete(func);
	}

	public Role getRole(String id) {
		return (Role) getSession().get(Role.class, id);
	}

	public void saveOrUpdateRole(Role role) {
		if (role.getId() == null || role.getId().trim().length() == 0)
			role.setId(null);
		getSession().saveOrUpdate(role);
	}

	public void removeRole(Role role) {
		role = (Role) getSession().get(Role.class, role.getId());
		if (role != null) {
			executeHQL("update User set role=null where role.id = ? ", role.getId());
			getSession().delete(role);
		}
	}

	public List<Role> getAllRoles() {
		return findByHQL("from Role order by name");
	}

	public List<Function> getAllTopFunctions() {
		return findByHQL("from Function where parent is null order by orderNo");
	}

	public boolean hasFunction(String roleId, String funcCode) {
		List result = findByHQL("from Role r join r.functions f where r.id = ? and f.code = ?", roleId, funcCode);
		if (result == null || result.size() == 0)
			return false;
		return true;
	}

}
